package com.example.zhinongbao.view;//package com.example.zhinongbao.view;
//
//import android.content.Intent;
//import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
//import android.os.Bundle;
//import android.view.View;
//import android.widget.ImageView;
//import android.widget.TextView;
//
//import androidx.annotation.Nullable;
//import androidx.appcompat.app.AppCompatActivity;
//
//import com.example.zhinongbao.R;
//import com.example.zhinongbao.entity.Goods;
//import com.example.zhinongbao.entity.Photo;
//
//import java.io.InputStream;
//import java.util.List;
//
//public class ProductDetailsActivity extends AppCompatActivity {
//    private ImageView photo;
//    private TextView goods_price;
//    private TextView goods_name;
//    private Goods goods;
//    private  ImageView mImageView;
//
//
//    @Override
//    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.actiivity_product_details);
//
//   //List<Photo> photoList = goods.getPhotoList();
//
////        Intent intent = getIntent();
////        if (intent != null) {
////            Bitmap bitmap = intent.getParcelableExtra("photoList");
////           mImageView= findViewById(R.id.photo);
////            if (bitmap != null) {
////                mImageView.setImageBitmap(bitmap);
////            }
////
////    }
////获取数据
//        goods=(Goods) getIntent().getSerializableExtra("goods");
//
//       //返回
//        findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//
//
//        //初始化控件
//        photo=findViewById(R.id.photo);
//        goods_name=findViewById(R.id.goods_name);
//        goods_price=findViewById(R.id.goods_price);
////设置数据
//        if (null!=goods) {
//
//            photo.setImageResource(goods.getImg());
//            goods_name.setText(goods.getName());
//            goods_price.setText(goods.getPrice()+"");
//
//        }
//    }
//
//    }
//获取数据
//package com.example.zhinongbao.view;
//
//
//import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
//import android.os.Bundle;
//import android.view.View;
//import android.widget.ImageView;
//import android.widget.TextView;
//
//import androidx.annotation.Nullable;
//import androidx.appcompat.app.AppCompatActivity;
//
//import com.example.zhinongbao.R;
//import com.example.zhinongbao.entity.Goods;
//import com.example.zhinongbao.entity.Photo;
//
//
//import java.util.List;
//
//public class ProductDetailsActivity extends AppCompatActivity {
//    private ImageView photo;
//    private TextView goods_price;
//    private TextView goods_name;
//    private Goods goods;
//
//    @Override
//    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.goods_activity);
//
//        // 获取传入的Goods对象
//        goods = (Goods) getIntent().getSerializableExtra("goods");
//
//        // 初始化控件
//        photo = findViewById(R.id.title_photo_show);
//        goods_name = findViewById(R.id.show_goods_name_detail);
//        goods_price = findViewById(R.id.show_price_goods);
//
//        // 设置返回按钮
////        findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
////            @Override
////            public void onClick(View v) {
////                finish();
////            }
////        });
//
//        // 设置数据
////        if (goods != null) {
////            // 获取Goods对象中的图片列表
////            List<Photo> photoList = goods.getPhotoList();
////            if (photoList != null && !photoList.isEmpty()) {
////                Photo firstPhoto = photoList.get(0); // 获取第一张图片
////                if (firstPhoto != null && firstPhoto.getData() != null) {
////                    // 将图片数据转换为Bitmap并设置到ImageView
////                    Bitmap bitmap = BitmapFactory.decodeByteArray(firstPhoto.getData(), 0, firstPhoto.getData().length);
////                    photo.setImageBitmap(bitmap);
////                }
////            }
////            goods_name.setText(goods.getName());
////            goods_price.setText(goods.getPrice() + "");
////        }
//        if (goods != null) {
//            // 获取Goods对象中的图片列表
//            List<Photo> photoList = goods.getPhotoList();
//            if (photoList != null && !photoList.isEmpty()) {
//                Photo firstPhoto = photoList.get(0); // 获取第一张图片
//                if (firstPhoto != null && firstPhoto.getData() != null) {
//                    // 压缩图片
//                    Bitmap compressedBitmap = compressBitmap(firstPhoto.getData(), 1280, 1280); // 压缩到1280x1280大小
//                    photo.setImageBitmap(compressedBitmap);
//                }
//            }
//            goods_name.setText(goods.getName());
//            goods_price.setText(goods.getPrice() + "");
//        }
//    }
//// 压缩图片的方法
//        private Bitmap compressBitmap(byte[] data, int maxWidth, int maxHeight) {
//            BitmapFactory.Options options = new BitmapFactory.Options();
//            options.inJustDecodeBounds = true; // 先获取图片的尺寸信息
//            BitmapFactory.decodeByteArray(data, 0, data.length, options);
//
//            // 计算缩放比例
//            float ratio = Math.min(
//                    (float) maxWidth / options.outWidth,
//                    (float) maxHeight / options.outHeight
//            );
//            if (ratio >= 1) return null; // 如果图片尺寸已经小于最大尺寸，则不需要压缩
//
//            options.inSampleSize = (int) ratio; // 设置采样率
//            options.inJustDecodeBounds = false; // 这次是真正的解码图片
//            return BitmapFactory.decodeByteArray(data, 0, data.length, options);
//
//    }
//}

// ...

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.zhinongbao.Model.IGoodsDetail;
import com.example.zhinongbao.Model.ProductDetailImpl;
import com.example.zhinongbao.R;
import com.example.zhinongbao.database.DBHelper;
import com.example.zhinongbao.entity.Goods;
import com.example.zhinongbao.entity.Photo;
import com.example.zhinongbao.presenter.AddGoodsPresenter;
import com.example.zhinongbao.presenter.ProductDetailsPresenter;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;
import java.util.List;

public class ProductDetailsActivity extends AppCompatActivity  {
    private ImageView photo;
    private TextView goods_price;
    private TextView goods_name;
    private Goods goods;
    private Context mContext;
    private int id; // 商品ID
    private Button gouwuche;
    private ProductDetailsPresenter presenter;
    private BottomSheetDialog bottomSheetDialog;
    // 根据商品ID查询商品信息的方法

//    @SuppressLint("Range")
//    private Goods queryGoodsById(int goodsId) {
//        SQLiteDatabase db = new DBHelper(this).getReadableDatabase();
//        Cursor cursor = null;
//        Goods goods = null;
//        List<Goods> list = new ArrayList<>();
//        try {
//            // 使用商品ID查询商品信息
//            cursor = db.query("goods", null, "_id = ?", new String[]{String.valueOf(goodsId)}, null, null, null);
//
//            if (cursor.moveToFirst()) {
//                // 假设Goods表的字段与Goods实体类的属性一一对应
//                goods = new Goods();
//                goods.setId(cursor.getInt(cursor.getColumnIndex("_id")));
//                goods.setName(cursor.getString(cursor.getColumnIndex("goods_name")));
//                goods.setPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
//                // 假设img字段存储的是图片路径或图片数据的某种表示
////                goods.setImg(cursor.getBlob(cursor.getColumnIndex("img")));
//                // 如果有Photo列表，这里也需要进行查询和设置
//            }
//
//            Uri photoUri = Uri.parse("content://com.example.zhinongbao.provider/photo");
//            Cursor photoCursor = mContext.getContentResolver().query(
//                    photoUri,
//                    null,
//                    "goods_id = ?",
//                    new String[]{String.valueOf(goodsId)},
//                    null);
//
//            if (photoCursor != null && photoCursor.moveToFirst()) {
//                do {
//                    Photo photo = new Photo();
//                    photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id")));
//                    photo.setData(photoCursor.getBlob(photoCursor.getColumnIndex("image")));
//                    goods.addPhoto(photo);
//                } while (photoCursor.moveToNext());
//            }
//            Log.d("", "goods ====== " + goods.toString());
//            list.add(goods);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (cursor != null) {
//                cursor.close();
//            }
//            db.close();
//        }
//
//        return goods;
//    }
    @SuppressLint("Range")
    private Goods queryGoodsById(int goodsId) {
        SQLiteDatabase db = new DBHelper(this).getReadableDatabase();
        Cursor cursor = null;
        Goods goods = null;
        try {
            // 使用商品ID查询商品信息
            cursor = db.query("goods", null, "_id = ?", new String[]{String.valueOf(goodsId)}, null, null, null);

            if (cursor.moveToFirst()) {
                // 假设Goods表的字段与Goods实体类的属性一一对应
                goods = new Goods();
                goods.setId(cursor.getInt(cursor.getColumnIndex("_id")));
                goods.setName(cursor.getString(cursor.getColumnIndex("goods_name")));
                goods.setPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                // 如果需要设置商品图片
                // goods.setImg(cursor.getBlob(cursor.getColumnIndex("img")));
            }

            // 确保 mContext 是一个有效的 Context 对象
            Context mContext = this; // 假设这是当前的 Activity 或者 Application 的 Context
            Uri photoUri = Uri.parse("content://com.example.zhinongbao.provider/photo");
            Cursor photoCursor = mContext.getContentResolver().query(
                    photoUri,
                    null,
                    "goods_id = ?",
                    new String[]{String.valueOf(goodsId)},
                    null);

            try {
                if (photoCursor != null && photoCursor.moveToFirst()) {
                    do {
                        Photo photo = new Photo();
                        photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id")));
                        photo.setData(photoCursor.getBlob(photoCursor.getColumnIndex("image")));
                        goods.addPhoto(photo); // 确保 Goods 类有 addPhoto 方法
                    } while (photoCursor.moveToNext());
                }
            } finally {
                if (photoCursor != null) {
                    photoCursor.close(); // 关闭 photoCursor 以避免资源泄露
                }
            }

            // 使用合适的标签和信息
            Log.d("queryGoodsById", "Goods info: " + goods.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close(); // 关闭 cursor
            }
            db.close(); // 关闭数据库
        }
        return goods;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_activity);
        // 初始化控件
        ProductDetailImpl productDetail =new ProductDetailImpl(this);
        presenter = new ProductDetailsPresenter(this,productDetail);

        photo = findViewById(R.id.title_photo_show);
        goods_name = findViewById(R.id.show_goods_name_detail);
        goods_price = findViewById(R.id.show_price_goods);
        gouwuche = findViewById(R.id.add_shopping_cart);
        // 根据ID查询商品信息
        // 从Intent中获取商品ID
        int goodsId = getIntent().getIntExtra("goodsId", -1);
        // -1 可以作为一个错误值，表示没有找到 ID

        if (goodsId != -1) {
            // 使用 goodsId 来查询商品信息
            Goods goods = queryGoodsById(goodsId);
            // 然后更新 UI 组件
            // ...
            // 获取商品的第一张图片并设置到ImageView
            List<Photo> photoList = goods.getPhotoList();
            if (photoList != null && !photoList.isEmpty()) {
                Photo firstPhoto = photoList.get(0);
                if (firstPhoto != null) {
                    Bitmap compressedBitmap = compressBitmap(firstPhoto, 800, 800); // 压缩图片
                    photo.setImageBitmap(compressedBitmap);
                }
            }
            goods_name.setText(goods.getName());
            goods_price.setText(goods.getPrice() + "");
        }
gouwuche.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int goodsId = getIntent().getIntExtra("goodsId", -1);
        Goods goods = queryGoodsById(goodsId);
        presenter.addCart(goodsId);

        Toast.makeText(ProductDetailsActivity.this, "已添加购物车", Toast.LENGTH_SHORT).show();
    }
});

};




    // 压缩图片的方法，现在接收Photo对象
    private Bitmap compressBitmap(Photo photo, int maxWidth, int maxHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(photo.getData(), 0, photo.getData().length, options);

        float ratio = Math.min(
                (float) maxWidth / options.outWidth,
                (float) maxHeight / options.outHeight
        );
        if (ratio >= 1) return null;

        options.inSampleSize = (int) ratio;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(photo.getData(), 0, photo.getData().length, options);
    }


}